package cn.hd01.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.repository.entity.Store;
import cn.hd01.service.StoreService;
import cn.hd01.service.UserService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.util.WebException;

@Controller
@RequestMapping("/store")
@Auth
public class StoreController {
	@Autowired
	private UserService userService;

	@Autowired
	private StoreService storeService;

	@RequestMapping(path = "/", method = RequestMethod.GET)
	public String userView(Model m) {
		m.addAttribute("users", userService.findAll());
		return "store";
	}

	@ResponseBody
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	private Page<Store> find(Store u, @PageableDefault Pageable pageable) {
		return storeService.find(u, pageable);
	}

	@ResponseBody
	@RequestMapping(path = "/delete{id}", method = RequestMethod.GET)
	private void find(@PathVariable("id") Integer id) {
		storeService.delete(id);
	}

	@ResponseBody
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	private void find(Store store) {
		if (store.getId() == null && storeService.exists(store.getName().trim())) {
			throw new WebException(HttpStatus.BAD_REQUEST, "门店名称" + store.getName() + "已经存在");
		}

		store.setName(store.getName().trim());
		storeService.save(store);
	}
}
